<template>
  <div class="business-detail">
    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <span>助贷保业务详情</span>
          <el-button @click="goBack" text>返回列表</el-button>
        </div>
      </template>

      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="3" border>
        <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ orderDetail.customerName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ orderDetail.customerPhone }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ orderDetail.productName }}</el-descriptions-item>
        <el-descriptions-item label="申请金额">{{ formatAmount(orderDetail.applyAmount) }}</el-descriptions-item>
        <el-descriptions-item label="批复金额">{{ formatAmount(orderDetail.approveAmount) }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ orderDetail.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="业务员">{{ orderDetail.salesUser }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(orderDetail.status)">{{ formatStatus(orderDetail.status) }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 流程步骤 -->
      <div class="process-steps">
        <h3>业务流程</h3>
        <el-steps :active="activeStep" finish-status="success" process-status="process" direction="horizontal"
          class="all-steps" align-center>
          <el-step v-for="(step, index) in stepConfig" :key="index" :title="step.title" :description="step.description"
            @click="handleStepClick(index)" class="clickable-step"></el-step>
        </el-steps>

        <!-- 详细流程内容 -->
        <div class="step-content-area">
          <el-card v-if="activeStep >= 0" shadow="never" class="step-content-card">
            <template #header>
              <div class="step-card-header">
                <span>{{ getStepTitle(activeStep) }}</span>
              </div>
            </template>

            <!-- 录单环节 -->
            <div v-if="activeStep === 0" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="客户姓名">{{ orderDetail.customerName }}</el-descriptions-item>
                <el-descriptions-item label="产品类型">{{ orderDetail.productType || '交易类' }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ orderDetail.remark || '无' }}</el-descriptions-item>
                <el-descriptions-item label="处理时间">{{ orderDetail.recordTime || orderDetail.applyTime
                }}</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.salesUser }}</el-descriptions-item>
                <el-descriptions-item label="营业执照" :span="2">
                  <el-image :src="recordImages[0]" fit="cover" class="detail-image"
                    :preview-src-list="[recordImages[0]]" />
                </el-descriptions-item>
                <el-descriptions-item label="产权证" :span="2">
                  <el-image :src="recordImages[1]" fit="cover" class="detail-image"
                    :preview-src-list="[recordImages[1]]" />
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 司法查询 -->
            <div v-if="activeStep === 1" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="查询结果">{{ orderDetail.judicialResult || '正常' }}</el-descriptions-item>
                <el-descriptions-item label="查询内容">征信查询、司法诉讼查询、失信查询</el-descriptions-item>
                <el-descriptions-item label="查询时间">{{ orderDetail.judicialTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="查询人员">{{ orderDetail.judicialUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.judicialUser }}</el-descriptions-item>
                <el-descriptions-item label="查询报告">
                  <el-button v-if="orderDetail.judicialFile" type="primary"
                    @click="downloadFile(orderDetail.judicialFile)">
                    下载查询报告
                  </el-button>
                  <el-button type="success" icon="Link">跳转至查询网页</el-button>
                </el-descriptions-item>
                <el-descriptions-item label="查询结果截图" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in judicialImages" :key="idx" :src="img" fit="cover"
                      class="detail-image" :preview-src-list="judicialImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 销售处理 -->
            <div v-if="activeStep === 2" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="处理结果">{{ salesResult[orderDetail.salesAction] || '-'
                }}</el-descriptions-item>
                <el-descriptions-item label="借款主体">{{ orderDetail.borrowerType || '企业' }}</el-descriptions-item>
                <el-descriptions-item label="借款人信息">{{ orderDetail.borrowerInfo || '-' }}</el-descriptions-item>
                <el-descriptions-item label="借款用途">企业经营周转</el-descriptions-item>
                <el-descriptions-item label="还款来源">经营收入</el-descriptions-item>
                <el-descriptions-item v-if="orderDetail.salesAction === 'initiate'"
                  label="客户来源">直客</el-descriptions-item>
                <el-descriptions-item v-if="orderDetail.salesAction === 'initiate'" label="配资情况">有，金额: {{
                  formatAmount(50000)
                }}</el-descriptions-item>
                <el-descriptions-item label="处理时间">{{ orderDetail.salesActionTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.salesUser }}</el-descriptions-item>
              </el-descriptions>

              <el-descriptions v-if="orderDetail.salesAction === 'initiate'" :column="2" border class="mt-20">
                <el-descriptions-item label="上家银行">{{ orderDetail.prevBank || '-' }}</el-descriptions-item>
                <el-descriptions-item label="还款金额">{{ formatAmount(orderDetail.repayAmount) }}</el-descriptions-item>
                <el-descriptions-item label="下家银行">{{ orderDetail.nextBank || '-' }}</el-descriptions-item>
                <el-descriptions-item label="批复金额">{{ formatAmount(orderDetail.approveAmount) }}</el-descriptions-item>
                <el-descriptions-item label="预计出款时间">2023-05-08</el-descriptions-item>
                <el-descriptions-item label="费用情况">渠道费: ¥3,000, 我司费用: ¥5,000, 杂费: ¥2,000</el-descriptions-item>
                <el-descriptions-item v-if="salesImages.length > 0" label="批复文件" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in salesImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="salesImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>

              <el-descriptions v-if="orderDetail.salesAction === 'reconsider'" :column="1" border class="mt-20">
                <el-descriptions-item label="复议内容">{{ orderDetail.reconsiderContent || '需要补充更多企业经营材料，包括最近半年的流水和纳税证明'
                }}</el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 面签安排 -->
            <div v-if="activeStep === 3" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="录单人员">{{ orderDetail.recorder || '-' }}</el-descriptions-item>
                <el-descriptions-item label="面签地点">公司总部会议室</el-descriptions-item>
                <el-descriptions-item label="确认配资">{{ orderDetail.confirmedFunding ? '是' : '否' }}</el-descriptions-item>
                <el-descriptions-item label="配资金额" v-if="orderDetail.confirmedFunding">{{ formatAmount(50000)
                }}</el-descriptions-item>
                <el-descriptions-item label="面签时间">{{ orderDetail.interviewTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.riskUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="面签预约凭证" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in interviewImages" :key="idx" :src="img" fit="cover"
                      class="detail-image" :preview-src-list="interviewImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 客户签约 -->
            <div v-if="activeStep === 4" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="签约地点">公司会议室</el-descriptions-item>
                <el-descriptions-item label="签约日期">{{ orderDetail.interviewTime ? new
                  Date(orderDetail.interviewTime).toLocaleDateString() : '-' }}</el-descriptions-item>
                <el-descriptions-item label="利率">{{ orderDetail.interestRate || '-' }} /天</el-descriptions-item>
                <el-descriptions-item label="预收费">{{ formatAmount(orderDetail.prepaidFee) }}</el-descriptions-item>
                <el-descriptions-item label="托管资料">{{ orderDetail.hasCustody ? '是' : '否' }}</el-descriptions-item>
                <el-descriptions-item v-if="orderDetail.hasCustody" label="托管资料清单">{{ orderDetail.custodyList || '-'
                }}</el-descriptions-item>
                <el-descriptions-item label="核行信息">{{ orderDetail.hasVerified ? '是' : '否' }}</el-descriptions-item>
                <el-descriptions-item v-if="orderDetail.hasVerified" label="核行方式">{{ orderDetail.verifyMethod || '-'
                }}</el-descriptions-item>
                <el-descriptions-item label="是否需办理顺位">否</el-descriptions-item>
                <el-descriptions-item label="是否办理赋强公证">否</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.warrantUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="签约现场照片" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in signImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="signImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>

              <el-descriptions :column="2" border class="mt-20">
                <el-descriptions-item label="出款通道信息" :span="2">
                  <el-table :data="loanChannels" border style="width: 100%" class="mt-10">
                    <el-table-column prop="channel" label="通道" width="180" />
                    <el-table-column prop="amount" label="出款金额" />
                    <el-table-column prop="expectedTime" label="预计出款时间" />
                  </el-table>
                </el-descriptions-item>
              </el-descriptions>

              <el-descriptions :column="2" border class="mt-20">
                <el-descriptions-item label="收集资料" :span="2">
                  <ul class="file-list">
                    <li v-for="(file, index) in orderDetail.collectedFiles" :key="index">
                      {{ file.name }}
                      <el-button type="primary" link @click="downloadFile(file.url)">查看</el-button>
                    </li>
                  </ul>
                </el-descriptions-item>
              </el-descriptions>

              <el-descriptions :column="2" border class="mt-20">
                <el-descriptions-item label="房产面积">138㎡</el-descriptions-item>
                <el-descriptions-item label="小区名称">海晟名苑</el-descriptions-item>
                <el-descriptions-item label="是否有二居">是</el-descriptions-item>
                <el-descriptions-item label="房屋类型">住宅</el-descriptions-item>
                <el-descriptions-item label="是否装修">是</el-descriptions-item>
                <el-descriptions-item label="是否限制交易">否</el-descriptions-item>
                <el-descriptions-item label="持证时间">2015-06-15</el-descriptions-item>
                <el-descriptions-item label="备注">小区位置优越，周边配套齐全</el-descriptions-item>
              </el-descriptions>

              <el-descriptions :column="2" border class="mt-20">
                <el-descriptions-item label="所属行业">互联网</el-descriptions-item>
                <el-descriptions-item label="工作类型">经营</el-descriptions-item>
                <el-descriptions-item label="公司名称">北京某科技有限公司</el-descriptions-item>
                <el-descriptions-item label="贷款品类">经营贷</el-descriptions-item>
                <el-descriptions-item label="贷款年限">5年</el-descriptions-item>
                <el-descriptions-item label="剩余年限">3年</el-descriptions-item>
                <el-descriptions-item label="是否循环贷">否</el-descriptions-item>
                <el-descriptions-item label="贷款时间">2020-05-15</el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 资料整理 -->
            <div v-if="activeStep === 5" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="资料是否齐全">{{ orderDetail.filecomplete ? '是' : '否' }}</el-descriptions-item>
                <el-descriptions-item label="需补充资料">无</el-descriptions-item>
                <el-descriptions-item label="资料整理人">{{ orderDetail.operationUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="整理分类">按客户-产品-日期归档</el-descriptions-item>
                <el-descriptions-item label="处理时间">{{ orderDetail.fileTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.operationUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="资料整理照片" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in fileImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="fileImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 风控审批 -->
            <div v-if="activeStep === 6" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="审批结果">{{ riskResultMap[orderDetail.riskResult] || '-'
                }}</el-descriptions-item>
                <el-descriptions-item label="审批评级">A</el-descriptions-item>
                <el-descriptions-item label="审批意见">客户资质良好，同意放款</el-descriptions-item>
                <el-descriptions-item v-if="orderDetail.pendingCondition" label="放款前待落实条件">{{
                  orderDetail.pendingCondition ||
                  '-' }}</el-descriptions-item>
                <el-descriptions-item label="审批时间">{{ orderDetail.riskApprovalTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.riskApprover || '-' }}</el-descriptions-item>
                <el-descriptions-item label="审批相关资料" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in riskImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="riskImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 项目上报 -->
            <div v-if="activeStep === 7" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="上报人员">{{ orderDetail.reportUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="上报银行">{{ orderDetail.nextBank || '-' }}</el-descriptions-item>
                <el-descriptions-item label="上报资料">贷款申请、征信报告、身份证明、资产证明</el-descriptions-item>
                <el-descriptions-item label="上报时间">{{ orderDetail.reportTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.operationManager || '-' }}</el-descriptions-item>
                <el-descriptions-item label="上报凭证" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in reportImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="reportImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 资方受理 -->
            <div v-if="activeStep === 8" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="受理机构">{{ orderDetail.nextBank || '-' }}</el-descriptions-item>
                <el-descriptions-item label="受理编号">ZD20230508001</el-descriptions-item>
                <el-descriptions-item label="受理时间">2023-05-08 10:40:12</el-descriptions-item>
                <el-descriptions-item label="当前状态">已受理</el-descriptions-item>
                <el-descriptions-item label="预计审批时间">3个工作日</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.operationUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="受理凭证" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in bankImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="bankImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 权证托管 -->
            <div v-if="activeStep === 9" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="托管资料">{{ orderDetail.custodyList || '-' }}</el-descriptions-item>
                <el-descriptions-item label="托管地点">{{ orderDetail.nextBank || '-' }}档案室</el-descriptions-item>
                <el-descriptions-item label="托管编号">KZ20230509003</el-descriptions-item>
                <el-descriptions-item label="托管时间">2023-05-09 14:20:35</el-descriptions-item>
                <el-descriptions-item label="托管凭证">已签收</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.warrantUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="托管照片" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in custodyImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="custodyImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 风控核实 -->
            <div v-if="activeStep === 10" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="核实内容">出款条件</el-descriptions-item>
                <el-descriptions-item label="核实项目">抵押登记、公证、保险</el-descriptions-item>
                <el-descriptions-item label="核实时间">2023-05-09 16:45:18</el-descriptions-item>
                <el-descriptions-item label="核实结果">具备出款条件</el-descriptions-item>
                <el-descriptions-item label="备注">所有资料齐全，符合放款条件</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.riskUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="核实资料" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in verifyImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="verifyImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 费用确认 -->
            <div v-if="activeStep === 11" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="费用类型">预收费</el-descriptions-item>
                <el-descriptions-item label="费用明细">服务费{{ formatAmount(orderDetail.prepaidFee * 0.8) }}，评估费{{
                  formatAmount(orderDetail.prepaidFee * 0.2) }}</el-descriptions-item>
                <el-descriptions-item label="确认金额">{{ formatAmount(orderDetail.prepaidFee) }}</el-descriptions-item>
                <el-descriptions-item label="支付方式">银行转账</el-descriptions-item>
                <el-descriptions-item label="确认时间">2023-05-10 09:30:21</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.operationUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="费用确认凭证" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in feeImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="feeImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 财务放款 -->
            <div v-if="activeStep === 12" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="放款金额">{{ formatAmount(orderDetail.approveAmount) }}</el-descriptions-item>
                <el-descriptions-item label="放款账户">{{ orderDetail.nextBank || '-' }}专用账户</el-descriptions-item>
                <el-descriptions-item label="收款账户">{{ orderDetail.customerName }}个人账户</el-descriptions-item>
                <el-descriptions-item label="放款渠道">{{ orderDetail.loanChannel || '-' }}</el-descriptions-item>
                <el-descriptions-item label="放款时间">{{ orderDetail.loanTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="交易流水号">ZF20230510985562</el-descriptions-item>
                <el-descriptions-item label="操作人">财务部-王出纳</el-descriptions-item>
                <el-descriptions-item label="放款凭证" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in loanImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="loanImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 确认到账 -->
            <div v-if="activeStep === 13" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="确认方式">电话回访</el-descriptions-item>
                <el-descriptions-item label="回访时间">2023-05-10 16:40:22</el-descriptions-item>
                <el-descriptions-item label="客户反馈">已收到款项</el-descriptions-item>
                <el-descriptions-item label="客户满意度">满意</el-descriptions-item>
                <el-descriptions-item label="回访记录">客户对服务表示满意，无异议</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.warrantUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="到账确认凭证" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in confirmImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="confirmImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 资料入库 -->
            <div v-if="activeStep === 14" class="step-detail">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="入库资料">合同资料、权证资料、银行流水等</el-descriptions-item>
                <el-descriptions-item label="入库编号">RK20230511032</el-descriptions-item>
                <el-descriptions-item label="入库时间">2023-05-11 10:15:38</el-descriptions-item>
                <el-descriptions-item label="归档位置">总部档案室</el-descriptions-item>
                <el-descriptions-item label="保管期限">长期</el-descriptions-item>
                <el-descriptions-item label="操作人">{{ orderDetail.operationUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="入库凭证" :span="2">
                  <div class="image-row">
                    <el-image v-for="(img, idx) in archiveImages" :key="idx" :src="img" fit="cover" class="detail-image"
                      :preview-src-list="archiveImages" :initial-index="idx" />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 后续流程 -->
            <div v-if="activeStep === 15" class="step-detail">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="当前状态">{{ orderDetail.currentStatus || '处理中' }}</el-descriptions-item>
              </el-descriptions>

              <div class="text-center mt-20">
                <el-button type="primary" @click="showFullProcess">查看完整流程</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 完整流程对话框 -->
    <el-dialog v-model="fullProcessVisible" title="完整业务流程" width="80%" destroy-on-close>
      <el-timeline>
        <el-timeline-item v-for="(activity, index) in processTimeline" :key="index" :timestamp="activity.timestamp"
          :type="activity.type" :icon="activity.icon">
          {{ activity.content }}
          <div class="timeline-detail" v-if="activity.detail">
            {{ activity.detail }}
          </div>
          <div class="timeline-operator" v-if="activity.operator">
            操作人：{{ activity.operator }}
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Document, Search, Operation, User, DocumentChecked, Files, Warning, UploadFilled, More } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

// 当前激活的步骤
const activeStep = ref(0);
const fullProcessVisible = ref(false);

// 定义接口以修复TypeScript错误
interface OrderDetail {
  id: string;
  orderNo: string;
  customerName: string;
  customerPhone: string;
  productName: string;
  productType: string;
  applyAmount: number;
  approveAmount: number;
  applyTime: string;
  status: string;
  salesUser: string;
  loanStatus: string;
  loanChannel: string;
  loanTime: string;
  remark: string;
  judicialResult: string;
  judicialTime: string;
  judicialUser: string;
  judicialFile: string;
  salesAction: string;
  borrowerType: string;
  borrowerInfo: string;
  prevBank: string;
  repayAmount: number;
  nextBank: string;
  salesActionTime: string;
  recorder: string;
  confirmedFunding: boolean;
  interviewTime: string;
  riskUser: string;
  collectedFiles: Array<{ name: string, url: string }>;
  interestRate: string;
  prepaidFee: number;
  hasCustody: boolean;
  custodyList: string;
  hasVerified: boolean;
  verifyMethod: string;
  warrantUser: string;
  filecomplete: boolean;
  fileTime: string;
  operationUser: string;
  riskResult: string;
  pendingCondition: string;
  riskApprovalTime: string;
  riskApprover: string;
  reportUser: string;
  reportTime: string;
  operationManager: string;
  currentStatus: string;
  recordTime: string;
  reconsiderContent: string;
}

// 订单详情
const orderDetail = reactive<OrderDetail>({
  id: '1',
  orderNo: 'AL20230501001',
  customerName: '张三',
  customerPhone: '13812345678',
  productName: '企业经营贷',
  productType: '交易类',
  applyAmount: 500000,
  approveAmount: 450000,
  applyTime: '2023-05-01 10:25:36',
  status: '1',
  salesUser: '李业务',
  loanStatus: '已放款',
  loanChannel: '招商银行',
  loanTime: '2023-05-10 15:30:45',
  remark: '客户有多套房产，资质良好',
  judicialResult: '正常',
  judicialTime: '2023-05-02 09:30:15',
  judicialUser: '王查询',
  judicialFile: 'https://example.com/file1.pdf',
  salesAction: 'initiate', // initiate, reconsider, abandon
  borrowerType: '企业',
  borrowerInfo: '张三公司',
  prevBank: '建设银行',
  repayAmount: 400000,
  nextBank: '招商银行',
  salesActionTime: '2023-05-03 10:25:36',
  recorder: '李录单',
  confirmedFunding: true,
  interviewTime: '2023-05-04 14:00:00',
  riskUser: '赵风控',
  collectedFiles: [
    { name: '身份证', url: 'https://example.com/id.pdf' },
    { name: '营业执照', url: 'https://example.com/license.pdf' },
    { name: '产权证', url: 'https://example.com/property.pdf' }
  ],
  interestRate: '0.05',
  prepaidFee: 5000,
  hasCustody: true,
  custodyList: '产权证、营业执照原件',
  hasVerified: true,
  verifyMethod: '电话',
  warrantUser: '张权证',
  filecomplete: true,
  fileTime: '2023-05-05 11:20:45',
  operationUser: '刘运营',
  riskResult: 'approved',
  pendingCondition: '提供最新的银行流水',
  riskApprovalTime: '2023-05-06 16:35:22',
  riskApprover: '黄经理',
  reportUser: '周上报',
  reportTime: '2023-05-07 09:15:33',
  operationManager: '杨主管',
  currentStatus: '资金已到账，待解押',
  recordTime: '2023-05-01 10:25:36',
  reconsiderContent: '需要补充提供更多财务资料'
});

// 销售处理结果映射
const salesResult = {
  'initiate': '发起',
  'reconsider': '复议',
  'abandon': '放弃'
};

// 风控审批结果映射
const riskResultMap = {
  'approved': '通过',
  'rejected': '否决',
  'returned': '退回',
  'escalated': '提级'
};

// 为时间线项目定义接口
interface TimelineItem {
  content: string;
  timestamp: string;
  type: 'primary' | 'success' | 'info' | 'warning' | 'danger';
  icon?: any;
  detail?: string;
  operator?: string;
}

// 完整流程时间线
const processTimeline = ref<TimelineItem[]>([
  {
    content: '销售录单',
    timestamp: '2023-05-01 10:25:36',
    type: 'primary',
    icon: Document,
    detail: '客户张三提交贷款申请，产品类型为企业经营贷',
    operator: '李业务'
  },
  {
    content: '司法查询',
    timestamp: '2023-05-02 09:30:15',
    type: 'success',
    icon: Search,
    detail: '司法查询结果正常，无不良记录',
    operator: '王查询'
  },
  {
    content: '销售处理-发起',
    timestamp: '2023-05-03 10:25:36',
    type: 'primary',
    icon: Operation,
    detail: '选择借款主体为企业，上家建设银行，下家招商银行',
    operator: '李业务'
  },
  {
    content: '面签安排',
    timestamp: '2023-05-04 14:00:00',
    type: 'primary',
    icon: User,
    detail: '安排李录单负责面签，确认配资情况',
    operator: '赵风控'
  },
  {
    content: '客户签约',
    timestamp: '2023-05-04 16:30:00',
    type: 'success',
    icon: DocumentChecked,
    detail: '客户签约完成，收集必要材料，利率0.05/天',
    operator: '张权证'
  },
  {
    content: '资料整理',
    timestamp: '2023-05-05 11:20:45',
    type: 'primary',
    icon: Files,
    detail: '资料整理完成，确认资料齐全',
    operator: '刘运营'
  },
  {
    content: '风控审批',
    timestamp: '2023-05-06 16:35:22',
    type: 'success',
    icon: Warning,
    detail: '风控审批通过，待落实条件：提供最新的银行流水',
    operator: '黄经理'
  },
  {
    content: '项目上报',
    timestamp: '2023-05-07 09:15:33',
    type: 'primary',
    icon: UploadFilled,
    detail: '项目正式上报',
    operator: '杨主管'
  },
  {
    content: '资方受理',
    timestamp: '2023-05-08 10:40:12',
    type: 'primary',
    detail: '招商银行已受理该笔业务',
    operator: '刘运营'
  },
  {
    content: '权证托管',
    timestamp: '2023-05-09 14:20:35',
    type: 'success',
    detail: '资料已托管，包括产权证、营业执照原件',
    operator: '张权证'
  },
  {
    content: '风控核实',
    timestamp: '2023-05-09 16:45:18',
    type: 'success',
    detail: '确认具备出款条件',
    operator: '赵风控'
  },
  {
    content: '费用确认',
    timestamp: '2023-05-10 09:30:21',
    type: 'primary',
    detail: '确认预收费已到账',
    operator: '刘运营'
  },
  {
    content: '财务放款',
    timestamp: '2023-05-10 15:30:45',
    type: 'success',
    detail: '放款成功，金额：¥450,000',
    operator: '财务部-王出纳'
  },
  {
    content: '权证确认到账',
    timestamp: '2023-05-10 16:40:22',
    type: 'primary',
    detail: '确认客户已收到款项',
    operator: '张权证'
  },
  {
    content: '资料入库',
    timestamp: '2023-05-11 10:15:38',
    type: 'info',
    detail: '所有资料已入库保存',
    operator: '刘运营'
  }
]);

// 返回列表页
const goBack = () => {
  router.push('/business-manage/assist-loan');
};

// 格式化金额
const formatAmount = (amount: number | undefined): string => {
  if (!amount) return '¥0.00';
  return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

// 获取状态对应的类型
const getStatusType = (status: string): 'primary' | 'success' | 'info' | 'warning' | 'danger' => {
  const statusMap: Record<string, 'primary' | 'success' | 'info' | 'warning' | 'danger'> = {
    '0': 'info',    // 待处理
    '1': 'primary', // 处理中
    '2': 'success', // 已完成
    '3': 'warning', // 需要补件
    '4': 'danger',  // 被拒绝
    '5': 'info'     // 已取消
  };
  return statusMap[status] || 'info';
};

// 格式化状态显示文本
const formatStatus = (status: string): string => {
  const statusTextMap: Record<string, string> = {
    '0': '待处理',
    '1': '处理中',
    '2': '已完成',
    '3': '需要补件',
    '4': '被拒绝',
    '5': '已取消'
  };
  return statusTextMap[status] || '未知状态';
};

// 下载文件
const downloadFile = (url: string) => {
  if (!url) {
    ElMessage.warning('文件链接不存在');
    return;
  }

  // 在新窗口打开文件
  window.open(url, '_blank');

  // 或者直接下载
  // const link = document.createElement('a');
  // link.href = url;
  // link.setAttribute('download', '');
  // document.body.appendChild(link);
  // link.click();
  // document.body.removeChild(link);
};

// 显示完整流程
const showFullProcess = () => {
  fullProcessVisible.value = true;
};

// 获取订单详情
const getOrderDetail = (id: string) => {
  // 实际项目中，这里需要调用API获取订单详情
  console.log('获取订单ID:', id);
  // 模拟获取数据
  // orderDetail.value = { ...mockData };

  // 设置当前步骤
  // 根据业务状态设置当前激活的步骤
  if (orderDetail.status === '2') {
    // 已完成状态，设置为最大步骤
    activeStep.value = 14;
  } else if (orderDetail.loanStatus === '已放款') {
    // 已放款状态
    activeStep.value = 12;
  } else if (orderDetail.reportTime) {
    // 已上报状态
    activeStep.value = 7;
  } else if (orderDetail.riskApprovalTime) {
    // 已风控审批状态
    activeStep.value = 6;
  } else if (orderDetail.fileTime) {
    // 已资料整理状态
    activeStep.value = 5;
  } else if (orderDetail.hasVerified) {
    // 已客户签约状态
    activeStep.value = 4;
  } else if (orderDetail.interviewTime) {
    // 已安排面签状态
    activeStep.value = 3;
  } else if (orderDetail.salesActionTime) {
    // 已销售处理状态
    activeStep.value = 2;
  } else if (orderDetail.judicialTime) {
    // 已司法查询状态
    activeStep.value = 1;
  } else if (orderDetail.applyTime) {
    // 已录单状态
    activeStep.value = 0;
  } else {
    // 默认状态
    activeStep.value = 0;
  }
};

// 获取步骤标题
const getStepTitle = (step: number): string => {
  const titles = [
    '录单环节',
    '司法查询',
    '销售处理',
    '面签安排',
    '客户签约',
    '资料整理',
    '风控审批',
    '项目上报',
    '资方受理',
    '权证托管',
    '风控核实',
    '费用确认',
    '财务放款',
    '确认到账',
    '资料入库'
  ];
  return titles[step] || '';
};

// 步骤配置
const stepConfig = [
  { title: '录单环节', description: '销售录入' },
  { title: '司法查询', description: '运营部查询' },
  { title: '销售处理', description: '销售决策' },
  { title: '面签安排', description: '风控安排' },
  { title: '客户签约', description: '权证部门' },
  { title: '资料整理', description: '运营整理' },
  { title: '风控审批', description: '风控审核' },
  { title: '项目上报', description: '运营上报' },
  { title: '资方受理', description: '银行受理' },
  { title: '权证托管', description: '材料托管' },
  { title: '风控核实', description: '条件确认' },
  { title: '费用确认', description: '预收费确认' },
  { title: '财务放款', description: '款项发放' },
  { title: '确认到账', description: '权证确认' },
  { title: '资料入库', description: '资料归档' }
];

// 处理步骤点击
const handleStepClick = (index: number) => {
  activeStep.value = index;
};

// 初始化图片数据
const recordImages = [
  'https://picsum.photos/200/150?random=1',
  'https://picsum.photos/200/150?random=2'
];

const judicialImages = [
  'https://picsum.photos/200/150?random=3',
  'https://picsum.photos/200/150?random=4'
];

const salesImages = [
  'https://picsum.photos/200/150?random=5',
  'https://picsum.photos/200/150?random=6'
];

const interviewImages = [
  'https://picsum.photos/200/150?random=7',
  'https://picsum.photos/200/150?random=8'
];

const signImages = [
  'https://picsum.photos/200/150?random=9',
  'https://picsum.photos/200/150?random=10'
];

const fileImages = [
  'https://picsum.photos/200/150?random=11',
  'https://picsum.photos/200/150?random=12'
];

const riskImages = [
  'https://picsum.photos/200/150?random=13',
  'https://picsum.photos/200/150?random=14'
];

const reportImages = [
  'https://picsum.photos/200/150?random=15',
  'https://picsum.photos/200/150?random=16'
];

const bankImages = [
  'https://picsum.photos/200/150?random=17',
  'https://picsum.photos/200/150?random=18'
];

const custodyImages = [
  'https://picsum.photos/200/150?random=19',
  'https://picsum.photos/200/150?random=20'
];

const verifyImages = [
  'https://picsum.photos/200/150?random=21',
  'https://picsum.photos/200/150?random=22'
];

const feeImages = [
  'https://picsum.photos/200/150?random=23'
];

const loanImages = [
  'https://picsum.photos/200/150?random=24',
  'https://picsum.photos/200/150?random=25'
];

const confirmImages = [
  'https://picsum.photos/200/150?random=26'
];

const archiveImages = [
  'https://picsum.photos/200/150?random=27',
  'https://picsum.photos/200/150?random=28'
];

// 出款通道数据
const loanChannels = [
  {
    channel: '通道1',
    amount: '¥300,000',
    expectedTime: '2023-05-12'
  },
  {
    channel: '通道2',
    amount: '¥150,000',
    expectedTime: '2023-05-15'
  }
];

// 页面初始化
onMounted(() => {
  const { id } = route.params;
  if (id) {
    getOrderDetail(id as string);
  } else {
    ElMessage.error('订单ID不存在，请返回列表重新选择');
    goBack();
  }
});
</script>

<style scoped>
.business-detail {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.detail-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.process-steps {
  margin-top: 30px;
}

.process-steps h3 {
  margin-bottom: 24px;
  font-weight: bold;
  font-size: 18px;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.process-steps h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}

.step-detail {
  padding: 15px 0;
  line-height: 2;
  color: #606266;
}

.step-detail p {
  margin-bottom: 8px;
}

.step-operator {
  color: #909399;
  margin-top: 8px;
  font-style: italic;
}

.step-pending {
  color: #909399;
  font-style: italic;
  padding: 10px 0;
}

.step-files {
  margin-bottom: 16px;
}

.file-list {
  padding-left: 20px;
  margin: 8px 0;
}

.file-list li {
  margin-bottom: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f9f9f9;
  padding: 8px 15px;
  border-radius: 4px;
  transition: all 0.3s;
}

.file-list li:hover {
  background-color: #f0f2f5;
}

.timeline-detail {
  color: #606266;
  margin-top: 8px;
  font-size: 14px;
  line-height: 1.6;
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.timeline-operator {
  color: #909399;
  margin-top: 5px;
  font-size: 13px;
  font-style: italic;
  text-align: right;
}

.ml-10 {
  margin-left: 10px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__header) {
  margin-bottom: 16px;
}

:deep(.el-descriptions__title) {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-tag) {
  font-weight: 500;
}

:deep(.el-steps) {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

:deep(.el-step__title) {
  font-weight: bold;
  font-size: 14px;
}

:deep(.el-step__title.is-process) {
  color: #409EFF;
  font-weight: 600;
}

:deep(.el-step__description) {
  font-size: 13px;
}

:deep(.el-step__icon.is-text) {
  border-width: 2px;
}

:deep(.el-step__head.is-process) {
  color: #409EFF;
  border-color: #409EFF;
}

:deep(.el-timeline-item__tail) {
  border-left: 2px solid #e4e7ed;
}

:deep(.el-timeline-item__node--normal) {
  left: -1px;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 26px;
}

:deep(.el-timeline-item__content) {
  font-weight: bold;
  color: #303133;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 13px;
}

.all-steps {
  margin-bottom: 20px;
  overflow-x: auto;
  white-space: nowrap;
  padding-bottom: 5px;
}

.step-content-area {
  margin-top: 30px;
}

.step-content-card {
  border-radius: 8px;
  margin-bottom: 20px;
  transition: all 0.3s;
  border: 1px solid #ebeef5;
}

.step-content-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.step-card-header {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.clickable-step {
  cursor: pointer;
}

:deep(.clickable-step .el-step__head),
:deep(.clickable-step .el-step__title),
:deep(.clickable-step .el-step__description) {
  transition: all 0.3s;
}

:deep(.clickable-step:hover .el-step__title) {
  color: #409EFF;
}

:deep(.clickable-step:hover .el-step__description) {
  color: #409EFF;
}

:deep(.clickable-step:hover .el-step__head:not(.is-process):not(.is-finish) .el-step__icon) {
  border-color: #409EFF;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__header) {
  padding: 16px 24px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  font-size: 18px;
  color: #303133;
}

:deep(.el-button--text) {
  font-weight: 500;
}

/* 确保步骤条在小屏幕上可以滚动查看 */
@media screen and (max-width: 1200px) {
  :deep(.el-steps--horizontal) {
    white-space: nowrap;
    overflow-x: auto;
  }

  :deep(.el-step) {
    display: inline-block;
  }
}

.step-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 15px 0;
}

.detail-image {
  width: 200px;
  height: 150px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  border: 1px solid #ebeef5;
}

.detail-image:hover {
  transform: none;
  box-shadow: none;
}

.text-center {
  text-align: center;
}

.mt-20 {
  margin-top: 20px;
}

.mt-10 {
  margin-top: 10px;
}

.document-title {
  font-weight: 600;
  font-size: 16px;
  margin: 20px 0 10px;
  color: #303133;
  position: relative;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.section-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  margin-bottom: 10px;
}

.action-buttons {
  margin: 15px 0;
  display: flex;
  gap: 10px;
}

.action-footer {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.image-title {
  font-size: 14px;
  color: #606266;
}

.image-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 5px;
}
</style>